<template>
  <div class="flex items-center justify-center min-h-screen bg-gray-50">
    <form @submit.prevent="onSubmit" class="w-80 bg-white p-8 rounded-lg shadow-lg transition-transform transform hover:scale-105">
      <h2 class="text-2xl font-bold mb-6 text-center text-green-600">注册</h2>

      <div class="mb-4">
        <input
          v-model.trim="nickname"
          type="text"
          placeholder="昵称"
          class="w-full border-gray-300 focus:border-green-500 focus:ring focus:ring-green-200 rounded-lg px-4 py-2 transition"
        />
      </div>

      <div class="mb-4">
        <input
          v-model.trim="account"
          type="text"
          autocomplete="username"
          placeholder="账号"
          class="w-full border-gray-300 focus:border-green-500 focus:ring focus:ring-green-200 rounded-lg px-4 py-2 transition"
        />
      </div>

      <div class="mb-4">
        <input
          v-model.trim="password"
          type="password"
          autocomplete="new-password"
          placeholder="密码"
          class="w-full border-gray-300 focus:border-green-500 focus:ring focus:ring-green-200 rounded-lg px-4 py-2 transition"
        />
      </div>

      <p v-if="error" class="text-red-500 mb-4 text-center">{{ error }}</p>

      <button type="submit" class="w-full bg-green-500 text-white py-2 rounded-lg hover:bg-green-600 transition">注册</button>

      <p class="mt-6 text-sm text-center">
        已有账号？
        <router-link to="/login" class="text-green-500 underline hover:text-green-600">去登录</router-link>
      </p>
    </form>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { required } from '@/utils/validators'
import { addUser, setCurrentUser } from '@/utils/storage'

const router = useRouter()
const account = ref('')
const nickname = ref('')
const password = ref('')
const error = ref('')

function validateRegisterForm(): boolean {
  if (!required(account.value) || !required(nickname.value) || !required(password.value)) {
    error.value = '请填写所有字段'
    return false
  }
  return true
}

function onSubmit() {
  if (!validateRegisterForm()) return

  const newUser = {
    account: account.value,
    nickname: nickname.value,
    password: password.value
  }

  const ok = addUser(newUser)

  if (!ok) {
    error.value = '该账号已被注册'
    return
  }

  setCurrentUser(newUser)
  router.push({ name: 'Chat' })
}
</script>
